package io.renren.modules.humanResources.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.humanResources.dao.AttendanceDao;
import io.renren.modules.humanResources.dto.AttendanceDTO;
import io.renren.modules.humanResources.entity.AttendanceEntity;
import io.renren.modules.humanResources.service.AttendanceService;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 打卡表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-03-27
 */
@Service
public class AttendanceServiceImpl extends CrudServiceImpl<AttendanceDao, AttendanceEntity, AttendanceDTO> implements AttendanceService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public QueryWrapper<AttendanceEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String realName = (String)params.get("realName");
        String attendanceType = (String)params.get("attendanceType");

        QueryWrapper<AttendanceEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        if (StringUtils.isNotBlank(attendanceType)) {
            wrapper.eq("attendance_type", Integer.valueOf(attendanceType));
        }
        if (StringUtils.isNotBlank(realName)) {
            List<SysUserDTO> userDtoList = sysUserService.getByRealName(realName);
            if (CollectionUtils.isNotEmpty(userDtoList)) {
                List<Long> collect = userDtoList.stream().map(SysUserDTO::getId).collect(Collectors.toList());
                wrapper.in("user_id", collect);
            } else {
                return null;
            }
        }

        return wrapper;
    }

    @Override
    public PageData<AttendanceDTO> attendancePage(Map<String, Object> params) {
        if (getWrapper(params) == null) {
            return new PageData<AttendanceDTO>(null, 0);
        }
        IPage<AttendanceEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );
        PageData<AttendanceDTO> pageData = getPageData(page, AttendanceDTO.class);
        pageData.getList().forEach(e -> {
            SysUserDTO sysUserDto = sysUserService.get(e.getUserId());
            e.setRealName(sysUserDto == null ? "" : sysUserDto.getRealName());
        });
        return pageData;
    }
}